//
//  CLLStatusPictureView.swift
//  CLWeiNo
//
//  Created by DDC on 2017/10/16.
//  Copyright © 2017年 DDC. All rights reserved.
//

import UIKit

class CLLStatusPictureView: UIView {
    
    /// 视图模型
    var listModel:CLLStatusViewModel?{
        didSet {
            calPicViewSize()
            // 设置配图模型中的urls属性
            urls = listModel?.picURLs
        }
    }
    /// 计算配图视图的高度
    fileprivate func calPicViewSize(){
        
        if listModel?.picURLs?.count == 1 {
            // 图片的尺寸
            let viewSize = listModel?.pictureViewSize ?? CGSize()
            // 获取图片
            let v = subviews[0]
            // 设置图片的frame布局
            v.frame = CGRect(x: 0, y: statusPictureOutterMargin, width: viewSize.width, height: viewSize.height)
        } else {
            // 多图或者没有图片, 恢复图片的九宫格布局尺寸
            let v = subviews[0]
            v.frame =  CGRect(x: statusPictureOutterMargin, y: statusPictureOutterMargin, width: statusPictureItemWidth, height: statusPictureItemWidth)
        }
        
        heightCons.constant = listModel?.pictureViewSize.height ?? 0
    }
    /// 配图模型数组
    var urls :[CLLStatusPicture]?{
        didSet{
            for iv in subviews {
                /// 隐藏所有的配图视图
                iv.isHidden = true
            }
            // 通过模型来加载数据
            var index = 0
            for url in urls ?? [] {
                
                let v = subviews[index] as! UIImageView
                v.cll_sdWebImage(urlString: url.thumbnail_pic, placeholderImage: nil)
                if urls?.count == 4 && index == 1 {
                    index += 1
                }
                // 显示图片
                v.isHidden = false
                index += 1
            }
        }
    }

    /// 配图视图的高度约束
    @IBOutlet weak var heightCons:NSLayoutConstraint!

    // 所有的内容最好是在显示之前就加载好,对性能方面有比较好的优化
    override func awakeFromNib() {
        
        setupPictureView()
    }
}

// MARK: - 布局cell中的图片
extension CLLStatusPictureView {
    fileprivate func setupPictureView(){
        
        // 没个图片的frame
        let rect = CGRect(x: statusPictureOutterMargin, y: statusPictureOutterMargin, width: statusPictureItemWidth, height: statusPictureItemWidth)
        clipsToBounds = true
        // 设置九宫格布局
        let count = 3
        for i in 0..<9 {
            let row = i / count
            let col = i % count
            
            // 创建图片视图
            let iv = UIImageView()
            
            // iv的显示模式样式设置
            iv.contentMode = .scaleToFill
            iv.clipsToBounds = true
            
            iv.frame = rect.offsetBy(dx: CGFloat(col) * (statusPictureItemWidth + statusPictureInnerMarger), dy: CGFloat(row) * (statusPictureItemWidth + statusPictureInnerMarger))
            // 添加到视图中
            addSubview(iv)
        }
        
    }
}
